// 薄弱知识点列表页面交互功能
document.addEventListener('DOMContentLoaded', function() {
    // 初始化进度条动画
    initProgressBars();

    // 绑定筛选功能
    initFilterFunctionality();

    // 绑定科目统计点击事件
    bindSubjectStatsEvents();

    // 绑定知识点卡片交互
    bindWeakPointCardEvents();

    // 初始化阈值指示器
    initThresholdIndicator();

    // 绑定导出功能
    bindExportFunctionality();
});

// 初始化进度条动画
function initProgressBars() {
    const progressBars = document.querySelectorAll('.mastery-progress-bar');
    progressBars.forEach(bar => {
        const width = bar.style.width;
        bar.style.width = '0';
        setTimeout(() => {
            bar.style.width = width;
        }, 300);
    });
}

// 初始化筛选功能
function initFilterFunctionality() {
    const thresholdSlider = document.getElementById('thresholdSlider');
    const thresholdValue = document.getElementById('thresholdValue');
    const subjectFilter = document.getElementById('subjectFilter');
    const masteryFilter = document.getElementById('masteryFilter');
    const applyFiltersBtn = document.getElementById('applyFilters');

    // 阈值滑块更新
    if (thresholdSlider && thresholdValue) {
        thresholdSlider.addEventListener('input', function() {
            thresholdValue.textContent = this.value + '%';
        });
    }

    // 应用筛选
    if (applyFiltersBtn) {
        applyFiltersBtn.addEventListener('click', function() {
            applyFilters();
        });
    }

    // 重置筛选
    const resetFiltersBtn = document.getElementById('resetFilters');
    if (resetFiltersBtn) {
        resetFiltersBtn.addEventListener('click', function() {
            resetFilters();
        });
    }
}

// 应用筛选
function applyFilters() {
    const thresholdSlider = document.getElementById('thresholdSlider');
    const subjectFilter = document.getElementById('subjectFilter');
    const masteryFilter = document.getElementById('masteryFilter');

    const threshold = thresholdSlider ? thresholdSlider.value / 100 : 0.6;
    const subject = subjectFilter ? subjectFilter.value : '';
    const mastery = masteryFilter ? masteryFilter.value : '';

    // 构建查询参数
    const params = new URLSearchParams();
    if (threshold !== 0.6) params.set('threshold', threshold);
    if (subject) params.set('subject', subject);
    if (mastery) params.set('mastery', mastery);

    // 显示加载状态
    showLoadingState();

    // 重新加载页面
    setTimeout(() => {
        window.location.href = window.location.pathname + '?' + params.toString();
    }, 500);
}

// 重置筛选
function resetFilters() {
    // 显示加载状态
    showLoadingState();

    // 重定向到无参数页面
    setTimeout(() => {
        window.location.href = window.location.pathname;
    }, 500);
}

// 绑定科目统计点击事件
function bindSubjectStatsEvents() {
    const subjectItems = document.querySelectorAll('.subject-stat-item');
    subjectItems.forEach(item => {
        item.addEventListener('click', function() {
            const subjectId = this.dataset.subjectId;
            if (subjectId) {
                // 跳转到科目详情页面
                window.location.href = `/analysis/subject/${subjectId}/`;
            }
        });
    });
}

// 绑定知识点卡片交互
function bindWeakPointCardEvents() {
    const weakPointCards = document.querySelectorAll('.weak-point-card');

    weakPointCards.forEach(card => {
        // 点击卡片主体跳转到详情页
        card.addEventListener('click', function(e) {
            // 排除按钮区域的点击
            if (!e.target.closest('.weak-point-actions')) {
                const knowledgeId = this.dataset.knowledgeId;
                if (knowledgeId) {
                    window.location.href = `/analysis/knowledge-point/${knowledgeId}/`;
                }
            }
        });

        // 悬停效果
        card.addEventListener('mouseenter', function() {
            this.style.boxShadow = '0 8px 30px rgba(0, 0, 0, 0.12)';
            this.style.transform = 'translateY(-2px)';
        });

        card.addEventListener('mouseleave', function() {
            this.style.boxShadow = '0 4px 20px rgba(0, 0, 0, 0.08)';
            this.style.transform = 'translateY(0)';
        });
    });

    // 绑定立即学习按钮
    const studyButtons = document.querySelectorAll('.study-btn');
    studyButtons.forEach(button => {
        button.addEventListener('click', function(e) {
            e.stopPropagation();
            const knowledgeId = this.dataset.knowledgeId;
            startStudySession(knowledgeId);
        });
    });
}

// 开始学习会话
function startStudySession(knowledgeId) {
    // 显示学习开始提示
    showNotification('开始学习薄弱知识点...', 'info');

    // 这里可以添加实际的学习会话逻辑
    // 例如：跳转到练习页面、打开学习模式等

    setTimeout(() => {
        // 模拟跳转到练习页面
        window.location.href = `/practice/start/?knowledge_point=${knowledgeId}&focus_mode=true`;
    }, 1000);
}

// 初始化阈值指示器
function initThresholdIndicator() {
    const thresholdIndicator = document.querySelector('.threshold-indicator');
    if (!thresholdIndicator) return;

    const currentThreshold = new URLSearchParams(window.location.search).get('threshold') || 0.6;
    const thresholdValue = thresholdIndicator.querySelector('.threshold-value');

    if (thresholdValue) {
        thresholdValue.textContent = (currentThreshold * 100).toFixed(0) + '%';
    }
}

// 绑定导出功能
function bindExportFunctionality() {
    const exportBtn = document.getElementById('exportWeakPoints');
    if (exportBtn) {
        exportBtn.addEventListener('click', exportWeakPointsData);
    }
}

// 导出薄弱知识点数据
function exportWeakPointsData() {
    const weakPoints = document.querySelectorAll('.weak-point-card');
    const exportData = {
        exportTime: new Date().toISOString(),
        threshold: new URLSearchParams(window.location.search).get('threshold') || 0.6,
        totalWeakPoints: weakPoints.length,
        weakPoints: []
    };

    weakPoints.forEach(card => {
        const name = card.querySelector('.weak-point-name').textContent;
        const mastery = card.querySelector('.mastery-value').textContent;
        const subject = card.querySelector('.weak-point-meta-item:first-child').textContent;

        exportData.weakPoints.push({
            name: name,
            mastery: mastery,
            subject: subject,
            knowledgeId: card.dataset.knowledgeId
        });
    });

    const dataStr = JSON.stringify(exportData, null, 2);
    const dataBlob = new Blob([dataStr], {type: 'application/json'});

    const url = URL.createObjectURL(dataBlob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `weak-points-${new Date().toISOString().split('T')[0]}.json`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    URL.revokeObjectURL(url);

    showNotification('薄弱知识点数据导出成功！', 'success');
}

// 显示加载状态
function showLoadingState() {
    const mainContent = document.querySelector('.container');
    const loadingOverlay = document.createElement('div');
    loadingOverlay.className = 'loading-state';
    loadingOverlay.innerHTML = '<div class="loading-spinner"></div>';
    loadingOverlay.style.cssText = `
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(255, 255, 255, 0.8);
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 9999;
    `;

    document.body.appendChild(loadingOverlay);
}

// 显示通知
function showNotification(message, type = 'info') {
    const notification = document.createElement('div');
    notification.className = `alert alert-${type} alert-dismissible fade show`;
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        z-index: 9999;
        min-width: 300px;
    `;
    notification.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;

    document.body.appendChild(notification);

    // 自动移除通知
    setTimeout(() => {
        if (notification.parentNode) {
            notification.parentNode.removeChild(notification);
        }
    }, 3000);
}

// 搜索功能
function initSearchFunctionality() {
    const searchInput = document.getElementById('searchWeakPoints');
    if (searchInput) {
        searchInput.addEventListener('input', function() {
            const searchTerm = this.value.toLowerCase();
            const weakPointCards = document.querySelectorAll('.weak-point-card');

            weakPointCards.forEach(card => {
                const name = card.querySelector('.weak-point-name').textContent.toLowerCase();
                const subject = card.querySelector('.weak-point-meta-item:first-child').textContent.toLowerCase();

                if (name.includes(searchTerm) || subject.includes(searchTerm)) {
                    card.style.display = '';
                } else {
                    card.style.display = 'none';
                }
            });
        });
    }
}

// 排序功能
function initSortFunctionality() {
    const sortSelect = document.getElementById('sortWeakPoints');
    if (sortSelect) {
        sortSelect.addEventListener('change', function() {
            const sortBy = this.value;
            sortWeakPoints(sortBy);
        });
    }
}

// 排序薄弱知识点
function sortWeakPoints(sortBy) {
    const container = document.querySelector('.weak-points-list');
    const weakPointCards = Array.from(document.querySelectorAll('.weak-point-card'));

    weakPointCards.sort((a, b) => {
        switch (sortBy) {
            case 'mastery-asc':
                return parseFloat(a.dataset.mastery) - parseFloat(b.dataset.mastery);
            case 'mastery-desc':
                return parseFloat(b.dataset.mastery) - parseFloat(a.dataset.mastery);
            case 'name-asc':
                return a.querySelector('.weak-point-name').textContent.localeCompare(b.querySelector('.weak-point-name').textContent);
            case 'name-desc':
                return b.querySelector('.weak-point-name').textContent.localeCompare(a.querySelector('.weak-point-name').textContent);
            default:
                return 0;
        }
    });

    // 重新插入排序后的元素
    weakPointCards.forEach(card => {
        container.appendChild(card);
    });

    showNotification(`已按${getSortLabel(sortBy)}排序`, 'info');
}

// 获取排序标签
function getSortLabel(sortBy) {
    const labels = {
        'mastery-asc': '掌握度升序',
        'mastery-desc': '掌握度降序',
        'name-asc': '名称升序',
        'name-desc': '名称降序'
    };
    return labels[sortBy] || '默认';
}

// 初始化所有功能
function initializeAll() {
    initProgressBars();
    initFilterFunctionality();
    bindSubjectStatsEvents();
    bindWeakPointCardEvents();
    initThresholdIndicator();
    bindExportFunctionality();
    initSearchFunctionality();
    initSortFunctionality();
}

// 页面加载完成后初始化
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initializeAll);
} else {
    initializeAll();
}